package com.example.demo;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    JobLauncher jobLauncher;
    @Autowired
    Job csvJob;
//    @Autowired
//    FlatFileItemReader itemReader;

    @GetMapping("/hello")
    public String hello() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        jobLauncher.run(csvJob, new JobParametersBuilder()
                .addDate("importtime",new Date())
                .toJobParameters());
        return "success";
    }

    @PostMapping("/users")
    public List<String> add(@Validated(UserValidationGroup1.class) User user, BindingResult bindingResult) {
        List<String> errors = new ArrayList<>();
        if(bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(objectError -> {
                errors.add(objectError.getDefaultMessage());
            });
        }
        return errors;
    }

    @PostMapping("/login")
    public List<String> login(@Validated(UserValidationGroup2.class) User user, BindingResult bindingResult) {
        List<String> errors = new ArrayList<>();
        if(bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(objectError -> {
                errors.add(objectError.getDefaultMessage());
            });
        }
        return errors;
    }
}
